<!-- 扫码上传-码详情
 * @Descripttion: 
 * @Author: 何伟伦 weilun@ssc-hn.com
 * @Date: 2024-05-07
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-05-07
-->
<template>
  <div class="code-card">
    <div class="code-card-header">
      <span class="code-card-header-title">{{ formState.goodName + formState.codeValue }} 码详情</span>
    </div>
    <a-form :model="formState" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }" ref="formRef" name="add_form" labelAlign="right">
      <a-row>
        <a-col :span="9">
          <a-form-item label="码值" name="codeValue">
            {{ formState.codeValue }}
          </a-form-item>
          <a-form-item label="商品" name="goodName">
            {{ formState.goodName }}
          </a-form-item>
          <a-form-item label="批次" name="batchName">
            {{ formState.batchName }}
          </a-form-item>
          <a-form-item label="图片" name="photoUrl" v-if="formState.photoUrl">
            <a-image :width="120" style="max-height: 120px" :src="formState.photoUrl" fallback="" />
          </a-form-item>
          <a-form-item label="说明">
            <a-tooltip>
              <template #title>{{ formState.notes }}</template>
              {{ ellipsis(formState.notes, 50) }}
            </a-tooltip>
          </a-form-item>
          <a-form-item label="添加说明" name="addNotes">
            <a-textarea :rows="8" v-model:value="formState.addNotes" placeholder="请输入" allow-clear showCount :maxlength="500" />
          </a-form-item>
          <a-form-item label=" " :colon="false" class="card-control">
            <a-button type="primary" @click="submit" :disabled="!formState.addNotes && !formState.extInfo">确定</a-button>
            <a-button type="primary" ghost @click="addAssociation">添加关联码</a-button>
            <a-button @click="closeCard">取消</a-button>
          </a-form-item>
        </a-col>
        <a-col :span="15">
          <a-form-item label="码状态" name="codeStatus">
            <a-tag color="green" v-if="formState.codeStatus === 1">正常</a-tag>
            <a-tag color="red" v-else-if="formState.codeStatus === 2">作废</a-tag>
            <span v-else>--</span>
          </a-form-item>
          <a-form-item label="渠道" name="channelsName">
            {{ formState.channelsName }}
          </a-form-item>
          <a-form-item label="关联问卷" name="contentTitle">
            <a v-if="formState.questionnaireRecordId" @click="openPaper">{{ formState.contentTitle }}</a>
            <span v-else>{{ formState.contentTitle }}</span>
            <a-button v-if="formState.questionnaireRecordId" type="primary" ghost style="margin-left: 16px;" @click="downloadFile">导出</a-button>
          </a-form-item>
          <a-form-item label="关联码" name="associationCodes">
            <a class="association-item" v-for="item in formState.associationCodes" :key="item.codeValue" @click="openAssociationCode(item.codeValue)"> {{ item.goodName }}{{ item.codeValue }} </a>
          </a-form-item>
          <a-form-item label="位置" name="location" v-if="formState.location">
            <span>{{ formState.location }}</span>
            <span> {{ formState.coordinates }}</span>
          </a-form-item>
          <a-form-item label="附件" name="fileName">
            {{ formState.fileName }}
          </a-form-item>
          <a-form-item name="extInfo" label="上传附件">
            <a-upload v-model:file-list="fileList" name="file" :maxCount="1" :action="uploadApi" :headers="{ authorization: token }" :before-upload="beforeUpload" @change="handleChange">
              <div class="upload-area">
                <div class="upload-icon"></div>
                <div class="upload-remind">点击或将文件拖拽到这里上传</div>
                <div class="upload-text">
                  请上传
                  <a-tooltip>
                    <template #title>支持jpg、jpeg、png、gif、bmp、tiff、pdf、doc、docx、rtf、md、odt、xls、xlsx、ppt、pptx、txt、csv、mp4、avi、mkv、flv、mp3、wav、aac、ogg、zip、rar、7z格式文件</template>
                    txt、pdf等格式文件
                  </a-tooltip>
                  ，大小在100M以内</div
                >
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <a-modal v-model:visible="visible" title="关联码">
      <template #footer>
        <a-button key="submit" type="primary" :disabled="codeList.length === 0" @click="confirmAssociation">确认关联</a-button>
      </template>
      <a-input-search ref="codeInput" v-model:value="searchParam.codeValue" placeholder="请在此输入码或选择后用扫码枪扫描" allowclear autofocus enter-button @search="search" />
      <div class="code-list-area">
        <div class="code-item" v-for="(item, index) in codeList" :key="item.codeValue">
          <span :title="`${item.codeValue} ${item.goodsName} ${item.batchName}`" class="code-item-text">{{ `${item.codeValue} ${item.goodsName} ${item.batchName}` }}</span>
          <a @click="deleteAssociation(index)"><minus-circle-outlined style="margin-right: 4px; margin-left: 4px" />删除</a>
        </div>
      </div>
      <div class="modal-tip">注意：关联码不可撤销，请谨慎操作</div>
    </a-modal>
  </div>
</template>

<script lang="ts" setup>
  import { MinusCircleOutlined } from '@ant-design/icons-vue'
  import { message, Upload } from 'ant-design-vue'
  import { nextTick, reactive, ref, watch } from 'vue'

  import { requestAssociationConfirm, requestAssociationInfo } from '/@/api/business/tracecode/codeAssociation'
  import { requestCodeDetail } from '/@/api/business/tracecode/codeInfo'
  import { requestSubmitReport } from '/@/api/business/tracecode/codeOperateLog'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { getToken } from '/@/storage'
  const token = getToken() || ''
  const uploadApi = `${import.meta.env.VITE_BASE_API_PATH}/contentFile/upload/V1`
  const fileList = ref([])
  const variable = reactive({
    confirmLoading: false,
    uploadLoading: false,
  })
  const visible = ref<boolean>(false)
  const loading = ref<boolean>(false)
  const searchParam = reactive({
    codeValue: '',
  })
  const codeInput = ref(null)
  const codeList = ref<CodeAssociationTypes.IResponse[]>([])

  const props = defineProps({
    data: { type: Object, default: null },
  })
  const emits = defineEmits(['onClose', 'openTab'])

  const formState = ref<any>({
    codeValue: null,
    goodName: null,
    channelsName: null,
    batchName: null,
    contentTitle: null,
    location: null,
    photoUrl: null,
    codeInfoId: null,
    notes: null,
    extInfo: null,
    questionnaireRecordId: null,
    codeStatus: null,
    associationCodes: [],
    fileName: null,
    addNotes: null,
    addFilename: null,
  })
  const ellipsis = (text: string, maxLength: number) => {
    if ((text?.length || 0) > maxLength) {
      return text.substr(0, maxLength - 3) + '...'
    }
    return text
  }

  /**
   * 搜索
   */
  const search = async () => {
    loading.value = true
    if (hasCode(searchParam.codeValue)) {
      message.warning('此码已存在')
    } else if (searchParam.codeValue === formState.value.codeValue) {
      message.warning('关联码不得与主码一致')
    } else {
      const { responseCode, responseData } = await requestCodeDetail({ codeValue: searchParam.codeValue })
      if (responseCode === HttpCodeEnum.SUCCESS) add(responseData)
      loading.value = false
    }
  }

  /**
   * 当前是否有对应的codeValue
   */
  const hasCode = (value) => {
    return codeList.value.find((item) => item.codeValue === value)
  }

  /**
   * 新增
   */
  const add = (data) => {
    codeList.value.unshift(data)
  }

  const addAssociation = () => {
    searchParam.codeValue = ''
    codeList.value = []
    visible.value = true
    nextTick(() => {
      codeInput.value && codeInput.value.focus()
    })
  }

  /**
   * 确认关联
   */
  const confirmAssociation = async () => {
    const { responseCode } = await requestAssociationConfirm({ codeValues: codeList.value.map((item) => item.codeValue), mainCode: formState.value.codeValue })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      searchParam.codeValue = ''
      codeList.value = []
      visible.value = false
      getAssociationInfo()
    }
  }
  /**
   * 删除关联码
   */
  const deleteAssociation = (codeIndex) => {
    codeList.value.splice(codeIndex)
  }

  const getAssociationInfo = async () => {
    const { responseCode, responseData } = await requestAssociationInfo({ codeValue: formState.value.codeValue })
    if (responseCode === HttpCodeEnum.SUCCESS) formState.value.associationCodes = responseData.associationCodes || []
  }

  watch(
    () => props.data,
    (value) => {
      if (value) {
        formState.value = { ...value, extInfo: null }
        // getAssociationInfo(value.codeValue)
      }
    },
    { immediate: true, deep: true },
  )

  const openPaper = () => {
    window.open(`/web/cms/question/analysis-detail?recordId=${formState.value.questionnaireRecordId}`)
  }

  const beforeUpload = (file) => {
    const fileSizeKB = file.size / 10244
    const isType = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.pdf', '.doc', '.docx', '.rtf', '.md', '.odt', '.xls', '.xlsx', '.ppt', '.pptx', '.txt', '.csv', '.mp4', '.avi', '.mkv', '.flv', '.mp3', '.wav', '.aac', '.ogg', '.zip', '.rar', '.7z'].includes(file.name.substr(file.name.lastIndexOf('.')).toLowerCase())
    if (!isType) {
      message.error('不支持的格式文件')
      return false || Upload.LIST_IGNORE
    } else if (fileSizeKB > 102400) {
      message.error('文件大小超过100MB，请选择一个较小的文件。')
      return false || Upload.LIST_IGNORE
    } else {
      return true
    }
  }

  /**
   * 提交
   */
  const submit = async () => {
    const { codeInfoId, extInfo, addNotes, addFilename, notes, fileName } = formState.value
    const { responseCode } = await requestSubmitReport({ codeInfoId, notes: addNotes || notes, extInfo, fileName: addFilename || fileName })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success('扫码上传成功')
      fileList.value = []
      formState.value.notes = addNotes || notes
      formState.value.addNotes = null
      formState.value.fileName = addFilename || fileName
      formState.value.extInfo = null
    }
  }

  /**
   * 关闭当前卡片tab
   */
  const closeCard = async () => {
    emits('onClose', formState.value.codeValue)
  }

  /**
   * 跳转打开关联码
   */
  const openAssociationCode = (codeValue) => {
    emits('openTab', codeValue)
  }

  const handleChange = (info) => {
    if (info.file.status === 'uploading') {
      variable.uploadLoading = true
      return
    }
    if (info.file.status === 'done') {
      console.log('info', info)
      message.success('上传成功')
      formState.value.extInfo = info.file.response.responseData
      formState.value.addFilename = info.file.name
      variable.uploadLoading = false
    }
    if (info.file.status === 'error') {
      variable.uploadLoading = false
      message.error(info.file.response.responseMessage || '上传错误')
    }
    if (info.file.status === 'removed' && info.fileList.length === 0) {
      formState.value.extInfo = null
      formState.value.addFilename = null
    }
  }

  // 创建一个点击事件触发下载
  function downloadFile() {
    // 文件下载地址
    const fileUrl = `${import.meta.env.VITE_BASE_API_PATH}/business/tracecode/codeAssociation/answerExport/V1?recordId=${formState.value.questionnaireRecordId}`;

    // 设置请求头
    const headers = new Headers();
    headers.append('Authorization', token);

    // 发起 Fetch 请求
    fetch(fileUrl, {
      method: 'GET',
      headers: headers,
    })
      .then(response => response.blob())
      .then(blob => {
        // 创建一个虚拟的链接元素，模拟点击下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = formState.value.contentTitle; // 设置下载文件名
        document.body.appendChild(link);

        // 模拟点击
        link.click();

        // 移除虚拟链接元素
        document.body.removeChild(link);
      })
      .catch(error => console.error('下载失败：', error));
  }

</script>

<style lang="less" scoped>
  .code-card {
    background: #fff;
    padding: 40px;

    ::v-deep(.ant-image) {
      overflow: hidden;
    }

    .code-card-header {
      font-size: 16px;
      font-weight: 500;
      color: #00474f;
      padding-bottom: 24px;

      &::before {
        content: '';
        width: 3px;
        height: 13px;
        display: inline-block;
        background: #13c2c2;
        margin-right: 3px;
      }

      .code-card-header-title {
        &::before {
          content: '';
          width: 2px;
          height: 10px;
          display: inline-block;
          background: #13c2c2;
          margin-right: 8px;
        }
      }
    }

    .association-item {
      font-weight: 400;
      color: #08979c;
      cursor: pointer;

      & + * {
        margin-left: 16px;
      }
    }

    .card-control {
      .ant-btn {
        & + * {
          margin-left: 8px;
        }
      }
    }

    .upload-area {
      width: 384px;
      height: 195px;
      background: rgb(0 0 0 / 2%);
      border-radius: 4px;
      border: 1px solid rgb(0 0 0 / 15%);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      .upload-icon {
        width: 48px;
        height: 48px;
        background-image: url('/@/assets/images/views/report/upload.png');
        margin-bottom: 20px;
      }

      .upload-remind {
        font-size: 16px;
        font-weight: 400;
        color: rgb(0 0 0 / 85%);
        margin-bottom: 4px;
      }

      .upload-text {
        font-size: 14px;
        font-weight: 400;
        color: rgb(0 0 0 / 43%);
      }
    }

    ::v-deep(.ant-upload-list-text-container) {
      width: 50%;
    }
  }

  .code-list-area {
    transition: height 1.5s;
    padding: 16px 0;
    min-height: 150px;

    .code-item {
      & + * {
        margin-top: 5px;
      }

      .code-item-text {
        max-width: 416px;
      }
    }
  }

  .modal-tip {
    font-weight: 500;
    font-size: 12px;
    color: red;
  }
</style>
